import axios from 'axios';
import { ElMessage } from 'element-plus'; //引入ElementPlus的弹窗提示工具
import router from "@/router"; //引入router实例对象

const request = axios.create({
    baseURL: "/api",
    timeout: 600000
});

request.interceptors.request.use((config)=>{
    const loginInfo = localStorage.getItem("loginInfo");
    if (loginInfo) {
        const loginUser = JSON.parse(loginInfo);
        config.headers.token = loginUser.token;
    }
    return config;
});

request.interceptors.response.use((response)=>{
    return response.data;
}, (error)=>{
    //↓↓↓↓↓如果响应状态码是401，就提示登录失败，然后跳转到/login↓↓↓↓↓
    if (error.response.status == 401) {
        ElMessage.error("登录失败，请重新登录");
        router.push("/login");
    }
    return Promise.reject(error);
});

export default request;